"use client"

import { useEffect, useState } from "react"
import { Sidebar } from "@/components/sidebar"
import { TopBar } from "@/components/top-bar"
import { Button } from "@/components/ui/button"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { ExternalLink, Copy, Trash2, Eye, EyeOff } from "lucide-react"
import { apiCall, mockGenerators } from "@/lib/mock-api"
import { useToast } from "@/hooks/use-toast"
import { formatDistanceToNow } from "date-fns"
import { zhCN } from "date-fns/locale"
import { Share2 } from "lucide-react" // Declare the Share2 variable here

interface Share {
  id: string
  fileId: number
  fileName: string
  fileType: string
  password?: string
  createdAt: string
  expireTime?: string
}

export function SharesLayout() {
  const [shares, setShares] = useState<Share[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState("")
  const { toast } = useToast()

  useEffect(() => {
    loadShares()
  }, [])

  const loadShares = async () => {
    try {
      setLoading(true)
      const data = await apiCall(
        "/api/shares",
        undefined,
        undefined,
        mockGenerators.sharesList,
      )
      setShares(data)
    } catch (error) {
      console.error("Failed to load shares:", error)
      toast({
        title: "加载失败",
        description: "无法加载分享记录",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }

  const copyLink = (shareId: string) => {
    const origin = typeof window !== "undefined" ? window.location.origin : ""
    const shareUrl = `${origin}${buildSharePath(shareId)}`
    navigator.clipboard.writeText(shareUrl)
    toast({
      title: "已复制",
      description: "分享链接已复制到剪贴板",
      variant: "success",
      duration: 3000,
    })
  }

  const buildSharePath = (shareId: string) => `/shared?shareId=${encodeURIComponent(shareId)}`

  const deleteShare = async (shareId: string) => {
    try {
      await apiCall(
        `/api/shares/${shareId}`,
        {
          method: "DELETE",
        },
        undefined,
        () => ({ success: true }),
      )
      setShares((prev) => prev.filter((s) => s.id !== shareId))
      toast({
        title: "已删除",
        description: "分享已删除",
        variant: "success",
        duration: 3000,
      })
    } catch (error) {
      toast({
        title: "删除失败",
        description: "无法删除分享",
        variant: "destructive",
        duration: 3000,
      })
    }
  }

  const filteredShares = shares.filter((share) => share.fileName.toLowerCase().includes(searchQuery.toLowerCase()))

  return (
    <div className="flex h-screen bg-background">
      <Sidebar />
      <div className="flex-1 flex flex-col overflow-hidden">
        <TopBar searchQuery={searchQuery} onSearchChange={setSearchQuery} />
        <main className="flex-1 overflow-auto p-6">
          <div className="max-w-6xl mx-auto">
            <h1 className="text-3xl font-bold mb-6">分享记录</h1>

            {loading ? (
              <div className="flex items-center justify-center h-64">
                <div className="text-muted-foreground">加载中...</div>
              </div>
            ) : filteredShares.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-64 text-center">
                <Share2 className="h-16 w-16 text-muted-foreground mb-4" />
                <p className="text-xl font-medium mb-2">暂无分享记录</p>
                <p className="text-muted-foreground">分享的文件会显示在这里</p>
              </div>
            ) : (
              <div className="space-y-4">
                {filteredShares.map((share) => (
                  <div
                    key={share.id}
                    className="border border-border rounded-lg p-4 hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <h3 className="font-medium text-lg mb-1 truncate">{share.fileName}</h3>
                        <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
                          <span className="flex items-center gap-1">
                            {share.password ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
                            {share.password ? "密码保护" : "无密码"}
                          </span>
                          <span>
                            创建于 {formatDistanceToNow(new Date(share.createdAt), { addSuffix: true, locale: zhCN })}
                          </span>
                        </div>
                        {share.password && share.password && (
                          <div className="mt-2 text-sm">
                            <span className="text-muted-foreground">访问密码: </span>
                            <span className="font-mono bg-muted px-2 py-1 rounded">{share.password}</span>
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => window.open(buildSharePath(share.id), "_blank")}
                          title="访问链接"
                        >
                          <ExternalLink className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => copyLink(share.id)}
                          title="复制链接"
                        >
                          <Copy className="h-4 w-4" />
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button
                              variant="outline"
                              size="sm"
                              className="text-destructive hover:text-destructive"
                              title="删除分享"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>确认删除该分享？</AlertDialogTitle>
                              <AlertDialogDescription>
                                删除后分享链接将立即失效，无法恢复。
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>取消</AlertDialogCancel>
                              <AlertDialogAction onClick={() => deleteShare(share.id)}>
                                确认删除
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </main>
      </div>
    </div>
  )
}
